package com.learn.thread;

import java.util.ArrayList;
import java.util.List;

public class PCWaitNotifyExample2 {
    public static void main(String[] args) {
        Buffer2 buffer2 = new Buffer2(1);
        new Thread(new Producer2(buffer2)).start();
        new Thread(new Consumer2(buffer2)).start();
    }
}

class Buffer2 {
    private final Object lock = new Object();
    private final List<Integer> item = new ArrayList<>();
    private final int maxCapacity;

    public Buffer2(int maxCapacity) {
        this.maxCapacity = maxCapacity;
    }

    public void produce(int value) {
        synchronized (lock) {
            while (item.size() == maxCapacity) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            item.add(value);
            System.out.println("生产者生产value：" + value + " 当前缓存区间大小为：" + item.size());
            lock.notifyAll();
        }
    }

    public void consumer() {
        synchronized (lock) {
            while (item.size() == 0) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            Integer remove = item.remove(0);
            System.out.println("当前消费者消费value：" + remove + " 当前缓存区间大小为：" + item.size());
            lock.notifyAll();
        }
    }
}

class Producer2 implements Runnable {
    private Buffer2 buffer2;

    public Producer2(Buffer2 buffer2) {
        this.buffer2 = buffer2;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            buffer2.produce(i);
        }
    }
}

class Consumer2 implements Runnable {
    private Buffer2 buffer2;

    public Consumer2(Buffer2 buffer2) {
        this.buffer2 = buffer2;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            buffer2.consumer();
        }
    }
}